import cloud from '@lafjs/cloud'
let userId
let dbName = "web-users"

export default async function (ctx: FunctionContext) {
  let now = Date.now()
  let { mobile, code, type } = ctx.body
  if (cloud.utils.isString(ctx.user.uid)) {
    userId = ctx.user.uid
  } else {
    userId = ctx.user.uid._id
  }
  let res = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: { _id: userId },
  });
  if (now > res.code_expire_time) return cloud.utils.requestReturn({ data: "", code: 500, msg: "验证码已过期" })
  if (code != res.code) return cloud.utils.requestReturn({ data: "", code: 500, msg: "验证码错误" })

  //查看这个手机号有没有被使用过
  let result = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: {
      $or: [
        { mobile: mobile.toString() },  // 匹配 string 类型[1,3](@ref)
        { mobile: Number(mobile) }     // 匹配 int 类型[1,3](@ref)
      ]
    }
  });

  let user_id //新的用户 id
  if (result && result._id) {
    if (result.hasOwnProperty(type) && result[type].openid) {
      return cloud.utils.requestReturn({ msg: "该手机号已被绑定", code: 500 })
    }
    let dataJson = {
      nickname: res.nickname,
      headimgurl: res.headimgurl,
    }

    if (type == 'pc') {
      dataJson['pc'] = res["pc"]
    } else {
      dataJson['h5'] = res["h5"]
    }
    await cloud.nw.db.update({
      dbName,
      whereJson: { mobile },
      dataJson
    });
    await cloud.nw.db.del({
      dbName,
      whereJson: { _id: res._id }
    });
    user_id = result._id
  } else {  //如果这个手机号没被绑定过
    user_id = await cloud.nw.db.update({
      dbName,
      whereJson: { _id: userId },
      dataJson: { mobile, baseInfo: { mobile } }
    });
  }
  return cloud.utils.requestReturn({ data: { token: cloud.utils.generateToken(user_id) } })
}


